package tsing.javase.excption;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import tsing.javase.common.bean.ResultVO;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice  // 设置拦截的范围，拦截自己包下的类
public class CommonExceptionHandler {

    final static Logger LOG = LoggerFactory.getLogger(CommonExceptionHandler.class);

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ResultVO handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder sb = new StringBuilder("校验失败:");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sb.append(fieldError.getField()).append("：").append(fieldError.getDefaultMessage()).append(", ");
        }
        String msg = sb.toString();
       return ResultVO.serverError(msg);
    }

    @ExceptionHandler({ConstraintViolationException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ResultVO handleConstraintViolationException(ConstraintViolationException ex) {
        return ResultVO.serverError(ex.getMessage());
    }

    /**
     *拦截businessException ,返回一个object 给到客户端
     */
    @ExceptionHandler(BusinessException.class) // Exception子类优先拦截
    @ResponseBody
    public Object exceptionHandler(BusinessException e){
        LOG.error("",e);//打印异常信息
        return ResultVO.serverError().setMsg(e.getMessage());
    }


    /**
     *拦截Exception ,返回一个object 给到客户端
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Object exceptionHandler(Exception e){
        LOG.error("",e);//打印异常信息
        return ResultVO.serverError().setMsg("调用异常");
    }


}
